package bank.dao.impl;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


import bank.dao.AccountDao;
import bank.entity.Account;
import bank.util.JdbcUtil;
import jdk.nashorn.internal.objects.annotations.Where;

public class AccountDaoImpl implements AccountDao {

	@Override
	public int add(String cardNo, String name, String password) {
		String sql ="insert into account(card_no,name,password) values('"+cardNo+"','"+name+"','"+password+"')";
		return JdbcUtil.update(sql);
	}

	@Override
	public int saveMoney(double money, String cardNo) {
		String sql ="update account set balance = balance+"+money+"where card_no='"+cardNo+"'";
		return JdbcUtil.update(sql);
	}

	@Override
	public int getMoney(double money, String cardNo) {
		String sql ="update account set balance = balance-"+money+"where card_no='"+cardNo+"'";
		return JdbcUtil.update(sql);
	}

	@Override
	public int transfer(double money, String from, String to) {
		String sql ="update account set balance = balance-"+money+"where card_no='"+from+"'";
		int n1 = JdbcUtil.update(sql);
		String sql2 ="update account set balance = balance+"+money+"where card_no='"+to+"'";
		int n2 = JdbcUtil.update(sql2);
		return n1+n2;
	}

	@Override
	public List<Account> findAll() {
		List<Account> list = new ArrayList<Account>();
		String sql = "select * from account";
		Connection conn =JdbcUtil.getConnection();
		try {
			Statement st =conn.createStatement();
			ResultSet rs= st.executeQuery(sql);
			while (rs.next()) {
				int id =rs.getInt("id");
				String cardNo = rs.getString("card_no");
				String name = rs.getString("name");
				double balance = rs.getDouble("balance");
				Account a =new Account();
				a.setBalance(balance);
				a.setCardNo(cardNo);
				a.setId(id);
				a.setName(name);
				list.add(a);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public Account checkPwd(String cardNo, String password) {
		Account a =null;
		String sql = "select * from account where card_no='"+cardNo+"'and password='"+password+"'";
		Connection conn = JdbcUtil.getConnection();
		try {
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			if (rs.next()) {
				int id =rs.getInt("id");
				String card = rs.getString("card_no");
				String name = rs.getString("name");
				double balance = rs.getDouble("balance");
				a.setBalance(balance);
				a.setCardNo(cardNo);
				a.setId(id);
				a.setName(name);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return a;
	}

}
